#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QHostAddress>
#include <QUdpSocket>
#include <QPalette>
#include <QIcon>
#include "QTextToSpeech"//语音模块

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{

    ui->setupUi(this);


    // 初始化语音模块（放在其他初始化代码之后）
    speech = new QTextToSpeech(this);
    speech->setLocale(QLocale::Chinese);  // 设置中文语音
    speech->setVolume(1.0);  // 最大音量

    // 检查是否支持中文语音
    if(speech->availableLocales().contains(QLocale::Chinese)) {
         qDebug() << "中文语音支持已启用";
     } else {
         QMessageBox::warning(this, "警告", "系统缺少中文语音支持");
     }



    // 初始化UDP
    udp = new QUdpSocket(this);
    if(!udp->bind(QHostAddress::Any, 5555)) {
        QMessageBox::critical(this, "Error", "Failed to bind UDP port");
    }

    // UI初始化
    QPalette pal = this->palette();
    pal.setBrush(QPalette::Background, QBrush(QPixmap(":/white.jpg")));
    this->setPalette(pal);

    // 按钮图标
    ui->pushButton_2->setIcon(QIcon(":/switch_off.png"));  // 使用按钮5的默认图标
    ui->pushButton_2->setIconSize(QSize(48,48));
    ui->pushButton_3->setIcon(QIcon(":/zidong.png"));  // 使用按钮5的默认图标
    ui->pushButton_3->setIconSize(QSize(48,48));
    ui->pushButton->setIcon(QIcon(":/dangqian.png"));
    ui->pushButton->setIconSize(QSize(48,48));
    ui->pushButton_5->setIconSize(QSize(48,48));
    ui->pushButton_5->setIcon(QIcon(":/switch_off.png"));


    // 动画初始化
    ui->label_5->setMinimumSize(200, 200);
    ui->label_5->setScaledContents(true);
    ui->label_5->setAlignment(Qt::AlignCenter);
    movie = new QMovie(":/fan2.gif");
    ui->label_5->setMovie(movie);
    movie->jumpToFrame(0); // 跳转到第一帧
    ui->label_5->update(); // 强制更新显示
    movie->stop();

    // 信号连接
    connect(udp, &QUdpSocket::readyRead, this, &Widget::readPendingDatagrams);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::sendCommand(const QString &command)
{
    const QHostAddress serverAddr("192.168.54.46");
    const quint16 serverPort = 6666;

    if(udp->writeDatagram(command.toUtf8(), serverAddr, serverPort) == -1) {
        QMessageBox::warning(this, "Error", "Failed to send command");
    }
}

void Widget::readPendingDatagrams()
{
    while (udp->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udp->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;
            udp->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
            QString response = QString::fromUtf8(datagram).trimmed();
            qDebug() << "收到服务器响应:" << response; // 调试用
            // 处理两种格式：
            // 1. 点击获取温度按钮的响应格式："Threshold: 50.00, Temperature: 29.11"
            // 2. 点击手动降温按钮的响应格式："Threshold set to 25.00"

            // 第一种响应格式处理
            if (response.startsWith("Threshold:") && response.contains("Temperature:")) {
                QStringList parts = response.split(", ");
                if (parts.size() >= 2) {
                    // 解析设定阈值
                    QString thresholdPart = parts[0];
                    QStringList thresholdPair = thresholdPart.split(": ");
                    if (thresholdPair.size() == 2) {
                        bool ok;
                        double threshold = thresholdPair[1].toDouble(&ok);
                        if (ok) {
                            currentThreshold = threshold;
                            ui->lcdNumber_2->display(threshold); // 显示到阈值LCD
                        }
                    }
                    // 解析当前温度
                    QString tempPart = parts[1];
                    QStringList tempPair = tempPart.split(": ");
                    if (tempPair.size() == 2) {
                        bool ok;
                        double temperature = tempPair[1].toDouble(&ok);
                        if (ok) {
                            ui->lcdNumber->display(temperature);// 显示到温度LCD
                            speech->say(QString("当前温度为%1度").arg(temperature));
                        }
                    }
                }
            }
            // 第二种响应格式处理（手动降温后的阈值更新）
            else if (response.startsWith("Threshold set to")) {
                QStringList parts = response.split(" ");
                if (parts.size() >= 4) {
                    bool ok;
                    double newThreshold = parts[3].toDouble(&ok);
                    if (ok) {
                        currentThreshold = newThreshold;
                        ui->lcdNumber_2->display(newThreshold); // 更新阈值显示
                        qDebug() << "阈值已更新至:" << newThreshold;
                    }
                }
            }
        }
}

// 手动降温按钮（原pushButton_5）
void Widget::on_pushButton_5_clicked()
{
    if(!isManualCooling) {
        sendCommand("open");
        ui->pushButton_5->setIcon(QIcon(":/switch_on.png"));
        movie->start();
        isManualCooling = true;

        // 语音提示
        speech->say("已开启手动降温模式");

        // 关闭自动模式
        if(isAutoCooling) {
            on_pushButton_2_clicked();
            movie->start();
        }
    } else {
        sendCommand("close");
        ui->pushButton_5->setIcon(QIcon(":/switch_off.png"));
        movie->stop();
        isManualCooling = false;
        // 语音提示
        speech->say("已关闭手动降温模式");
    }
}

// 获取温度按钮（原pushButton）
void Widget::on_pushButton_clicked()
{
    sendCommand("getTp");
    speech->say("正在获取最新温度");
}

// 自动降温按钮（原pushButton_2）
void Widget::on_pushButton_2_clicked()
{
    if(!isAutoCooling) {
         QString temp = ui->comboBox->currentText().remove("°C").trimmed();
         sendCommand(QString("setThreshold:%1").arg(temp));
         sendCommand(QString("auto-on"));

         // 切换为开启图标（复用按钮5的开启图标）
         ui->pushButton_2->setIcon(QIcon(":/switch_on.png"));
         movie->start();
         //ui->pushButton_2->setText("关闭自动降温");
         isAutoCooling = true;
         // 语音提示
         speech->say(QString("已开启自动降温，设定阈值为%1度").arg(temp));
         if(isManualCooling) {
             on_pushButton_5_clicked();
             movie->start();
         }
     } else {
         sendCommand("auto-off");

         // 切换回默认图标（复用按钮5的关闭图标）
         ui->pushButton_2->setIcon(QIcon(":/switch_off.png"));
         movie->stop();
         //ui->pushButton_2->setText("开启自动降温");
         isAutoCooling = false;
         // 语音提示
         speech->say("已关闭自动降温模式");
     }
}
